var showcase = {
	categories: {
		list: null,
		current: null,
		select: null	
	},
	
	subcategories: {
		list: null,
		current: null,
		select: null	
	},
	
	liDragOptions: {
		appendTo: 'body',
		helper: 'clone',
		start: function(e, ui) {
			$('.vitrine .central-content .current .drop-handler').show();
			$('.vitrine .central-content .lst-tabs .tab-content ul').addClass('target');
		}, 
		stop: function(e, ui) {
			$('.vitrine .central-content .current .drop-handler').hide();	
			$('.vitrine .central-content .lst-tabs .tab-content ul').removeClass('target');
		}
	},
	
	gridProds: {
		list: '',
		length: 0,
		add: function  (id) {
			showcase.gridProds.list += id + '_';
			showcase.gridProds.length++;
			showcase.gridProds.updateCount();
		},
		remove: function  (id) {
			showcase.gridProds.list = showcase.gridProds.list.replace(id + '_', '');
			showcase.gridProds.length--;
			showcase.gridProds.updateCount();
		},
		check: function  (id) {
			var exists = showcase.gridProds.list.indexOf(id) >= 0; 
			return exists;
		},
		updateCount : function(){
			$('.txt-quant strong').text('{0} produto{1}'.format(showcase.gridProds.length, showcase.gridProds.length == 1 ? '' : 's'));
		},
	},
	
	init : function( ){
		$.getScriptSafe('/static/settings.js', showcase.loadMlPack);
		
		$('select')
			.fadeTo(0,0)
			.bind('change', function (e) {
				var sel = $(e.currentTarget);
				var lbl = sel.prev();
				lbl.text(sel.find('option:selected').text()._slice(25));
			});
	},
	
	loadMlPack : function(){
		$.getScriptSafe('/static/js/lib/ml-utils.js', showcase.allLoadsComplete);
	},
	
	allLoadsComplete: function () {
		$('.vitrine .central-content .lst-grid ul').sortable({ tolerance: 'pointer'	});
		$('.vitrine .central-content .drop-handler').droppable({ drop: showcase.addProd });
		$('.vitrine .central-content .lst-tabs > ul > li:eq(0)').addClass('current');
		$('.vitrine .central-content .lst-tabs > ul > li .nav-tab').bind('click', function(e){
			e.preventDefault();
			$('.vitrine .central-content .lst-tabs > ul > li').removeClass('current');
			$(e.currentTarget).parent().addClass('current');
			showcase.adjustPosition();
		});
		
		showcase.categories.select = $('.vitrine .left-content .box-search select:eq(0)');
		showcase.subcategories.select = $('.vitrine .left-content .box-search select:eq(1)');

		showcase.adjustPosition();
		showcase.loadCats();
		showcase.readCurrentProds();

		showcase.categories.select.bind('change', function (e) {
			if(e.currentTarget.selectedIndex > 0){
				showcase.loadSubCats(e.currentTarget.value);
			}else{
				showcase.subcategories.select
					.attr({ disabled: 'disabled' })
					.prev().fadeTo(0, .6).text(showcase.subcategories.select.find('option:eq(0)').text())
					.next()[0].selectedIndex = 0;
			}
		});
		showcase.subcategories.select.attr('disabled', 'disabled').prev().fadeTo(0, .6);
		
		$('.vitrine .left-content .box-search a').bind('click', showcase.getSearch);//.trigger('click');
		$('.vitrine .grp-nav-footer .nav-next').bind('click', showcase.postForm);
		
		var txtSearch = $('#txt-search');
		txtSearch.val( txtSearch.attr('rel') )
		.bind('focus', function (e) {
			if( txtSearch.val() == txtSearch.attr('rel') ) txtSearch.val('')
		}).bind('blur', function (e) {
			if( txtSearch.val() == '' ) txtSearch.val(txtSearch.attr('rel'))
		});
		
		showcase.review.init();
	},
	
	readCurrentProds: function(attribute){
		var timeInterval = 0;
		$.each( $('form input[id*="product"]'), function(i, el) {
			var idProd = $(el).val();
			
			if( idProd != ""){
				var index = i + 1;
				var div = $('<div/>').addClass('grid-mode');
				var li = $('<li/>').append(div).addClass('loading').attr('id', idProd);

				var tab = $('.vitrine .lst-tabs ul > li:eq({0}) .lst-grid ul'.format((index / 12).ceil() - 1))
				.append(li)
				.sortable('refresh');
				
				showcase.gridProds.add(idProd);
				
				setTimeout(showcase.getProdDetails, (500 * timeInterval), idProd, li);
				timeInterval++;
			}
		});
	},
	
	getProdDetails: function(idFull, li){
		var id = idFull.substr(0, 7);
		var model = idFull.substr(7, 2);
		var jData = new mlSerializer()
			.add('product_id', id)
			.add('model', model)
			.render();
		
		$.ajax({
			type: 'post',
			dataType: 'json',
			context: li,
			contentType: 'application/json',
			processData: false,
			data: jData,
			url: settings.product.fetch,
			success: showcase.getProdDetailsComplete 
		});
	},
	
	getProdDetailsComplete: function(data, stt, xhr){
		var el = data.product;
		var li = this;
		var urlRegular = '{0}/{1}'.format( settings.product.imgBaseUrl, el.media.images.thumbs[0]).replace(/\/\//g, '/').replace(/http:\//g, 'http://');
		var gridMode = li.find('.grid-mode');

		$('<img/>')
			.attr('src', '{0}'.format(urlRegular))
			.appendTo(gridMode);

		$('<div/>')
			.addClass('desc')
			.append( $('<p/>').text(el.name) )
			.append( $('<span/>').text(el.price_info.cash_price.formatBrMoney()))
			.appendTo(gridMode);
		
		$('<a/>')
			.text('Excluir este produto')
			.attr({
				title: 'Excluir este produto',
				href: '#'
			})
			.addClass('nav-rm-product')
			.bind('click', showcase.removeProd)
			.appendTo(gridMode);
		
		$('<a/>')
			.text('Adicionar sua opnião')
			.attr({
				title: 'Adicionar sua opnião',
				href: '#'
			})
			.addClass('nav-add-opinion')
			.bind('click', showcase.addOpinion)
			.appendTo(gridMode);
	
		li.removeClass('loading')	
	},
	
	loadCats: function () {
		$.ajax({
			type: 'post',
			dataType: 'json',
			contentType: 'application/json',
			processData: false,
			url: settings.category.fetch,
			success: showcase.loadCatsComplete 
		});
	},
	
	loadCatsComplete: function (data, xhr, stt) {
		var opt = showcase.categories.select.find('option:eq(0)').clone();
		showcase.categories.select.empty().append(opt);	

		showcase.categories.list = data.categories;
		$.each(showcase.categories.list, function (i, el) {
			var opt = $('<option/>').val(el.id).text(el.name);
			showcase.categories.select.append(opt);
		});
	},
	
	loadSubCats: function(e){
		
		showcase.subcategories.select.attr('disabled', 'disabled').prev().fadeTo(0, .6);

		$.ajax({
			type: 'post',
			dataType: 'json',
			contentType: 'application/json',
			processData: false,
			data: new mlSerializer().add('category_id', e).render(),
			url: settings.category.subCategoryFetch,
			success: showcase.loadSubCatsComplete 
		});
	},
	
	loadSubCatsComplete: function(data, xhr, stt){
		var opt = showcase.subcategories.select.find('option:eq(0)').clone();
		showcase.subcategories.select.empty().append(opt);	

		showcase.subcategories.list = data.subcategories;

		$.each(showcase.subcategories.list, function (i, el) {
			var opt = $('<option/>').val(el.id).text(el.name);
			showcase.subcategories.select.append(opt);	
		});
		
		showcase.subcategories.select.removeAttr('disabled').prev().fadeTo(500, 1);
	},
	
	getSearch: function(e){
		e.preventDefault();
		
		var catVal = showcase.categories.select.val() == showcase.categories.select.find('option:eq(0)').val() ? '' : showcase.categories.select.val();
		var subCatVal = showcase.subcategories.select.val() == showcase.subcategories.select.find('option:eq(0)').val() ? '' : showcase.subcategories.select.val();
		var txtVal = $('#txt-search').val() == $('#txt-search').attr('rel') ? '' : $('#txt-search').val();
		
		if(catVal == '' && txtVal == '') {
			mlControls.alert(settings.product.msgValidate1);
			return;
		}
		
		$('.vitrine .left-content .box-results').addClass('loading');
		
		var jData = new mlSerializer()
			.add('category', catVal)
			.add('subcategory', subCatVal)
			.add('term', txtVal)
			.render();
		
		$.ajax({
			type: 'post',
			dataType: 'json',
			contentType: 'application/json',
			processData: false,
			data: jData,
			url: settings.product.search,
			success: showcase.getSearchComplete 
		});
	},
	
	getSearchComplete: function(data, xhr, stt){
		$('.vitrine .left-content .box-results').removeClass('loading');
		$('.vitrine .left-content .box-results ul').empty();
		
		$.each(data.products, function (i, el) {
			var idFull = el.id;
			
			if(showcase.gridProds.check(idFull)) return;

			// - - - - - - - - - - - - - - - - - - - - 
			
			var urlThumb = 'url("{0}/{1}")'.format( settings.product.imgBaseUrl, el.media.images.thumbs).replace(/\/\//g, '/').replace(/http:\//g, 'http://');
			var listMode = $('<div/>').addClass('list-mode');
			$('<img/>')
				.attr('src', '/static/img/shared/vitrine/bg-mask-img.png')
				.css({backgroundImage: urlThumb})
				.appendTo(listMode);
			
			$('<div/>')
				.text(el.name._slice(60))
				.addClass('desc')
				.append( $('<span/>').text(el.price_info.cash_price.formatBrMoney()))
				.appendTo(listMode);
			
			// - - - - - - - - - - - - - - - - - - - - 
			
			var urlRegular = '{0}/{1}'.format( settings.product.imgBaseUrl, el.media.images.regulars).replace(/\/\//g, '/').replace(/http:\//g, 'http://');
			var gridMode = $('<div/>').addClass('grid-mode');
			
			$('<img/>')
				.attr('src', '{0}'.format(urlRegular))
				.appendTo(gridMode);

			$('<div/>')
				.addClass('desc')
				.append( $('<p/>').text(el.name) )
				.append( $('<span/>').text(el.price_info.cash_price.formatBrMoney()))
				.appendTo(gridMode);
			
			$('<a/>')
				.text('Excluir este produto')
				.attr({
					title: 'Excluir este produto',
					href: '#'
				})
				.addClass('nav-rm-product')
				.appendTo(gridMode);
			
			$('<a/>')
				.text('Adicionar sua opnião')
				.attr({
					title: 'Adicionar sua opnião',
					href: '#'
				})
				.addClass('nav-add-opinion')
				.appendTo(gridMode);
			
			// - - - - - - - - - - - - - - - - - - - - 

			var li = $('<li/>')
				.addClass('ml-li-prod-item')
				.append(listMode)
				.append(gridMode)
				.attr('id', idFull)
				.appendTo('.vitrine .left-content .box-results ul');
		});

		$('.vitrine .left-content .box-results ul li').draggable( showcase.liDragOptions );
	},
	
	addProd: function(e, ui){
		var ul = $(this).parent().find('ul');
		
		if(ul.find('li').length == 12) return;
		
		var id = $(ui.draggable).attr('id');
		var newLi = $('<li/>')
			.html($(ui.draggable).html())
			.attr('id', id);
			
		newLi.find('.nav-rm-product').bind('click', showcase.removeProd);	
		newLi.find('.nav-add-opinion').bind('click', showcase.addOpinion);	
		
		ul.append(newLi).sortable('refresh');
		
		$(ui.draggable).hide();
		
		showcase.gridProds.add(id);
	},
	
	removeProd: function(e){
		e.preventDefault();
		
		mlControls.confirm(settings.product.msgValidate2, function (ok) {
			if(!ok) return;
			
			var li = $(e.currentTarget).parent().parent();
			var id = li.attr('id');
		
			showcase.gridProds.remove(id);
			li.remove();
		})
		
		/*
		if(window.confirm('Tem certeza que deseja excluir este produto?')){
			var li = $(e.currentTarget).parent().parent();
			var id = li.attr('id');
		
			showcase.gridProds.remove(id);
			li.remove();
		}
		*/
	},
	
	postForm: function(e){
		e.preventDefault();
		
		var index = 12;
		
		$('form > div input').removeAttr('value');
		
		$.each($('.lst-tabs > ul > li'), function (i1, el1) {
			$.each($(el1).find('.lst-grid ul li'), function (i2, el2) {
				var hiddenId = (i1 * index) + (i2 + 1);
				$('input#product_' + hiddenId).val($(el2).attr('id'))
			});
		})
		
		$('form').submit();
	},
	
	addOpinion: function(e){
		e.preventDefault();
		var el = $(e.currentTarget);
		var prodId = el.parent().parent().attr('id');
		var userId = $('input[name="profile_key"]').val();
		showcase.review.show(prodId, userId);
	},
	
	review:{
		prodId: null,
		mlvcId: null,
		reviewId: null,
		mode: null,
		
		init: function(){
			trace('review : init');
		},
		
		show: function(prodId, mlvcId, action){
			trace('review : show');
			showcase.review.prodId = prodId;
			showcase.review.mlvcId = mlvcId;
			showcase.review.reviewId = null;
			showcase.review.mode = null;
			
			mlModal.open({
				width: 680,
				height: 365,
				title: 'Sua opnião',
				urlContent: '/static/templates/modal-review.html',
				loadComplete: showcase.review.templateLoaded
			});
		},
		
		templateLoaded: function(){
			mlModal.showLoading();
			
			var jData = new mlSerializer()
				.add('product_id', showcase.review.prodId)
				.add('author_id', showcase.review.mlvcId)
				.render();

			$.ajax({
				type: 'post',
				dataType: 'json',
				contentType: 'application/json',
				processData: false,
				data: jData,
				url: settings.review.fetch,
				success: showcase.review.loaded
			});
		},
		
		loaded: function(data, stt, xhr){
			var el = $('#{0}'.format(showcase.review.prodId));
			$('.modal-review .inner .prod-detail p').text(el.find('.grid-mode .desc p').text());
			$('.modal-review .inner .prod-detail img').css('background-image', 'url("{0}")'.format(el.find('.grid-mode img').attr('src')));
			$('.modal-review .inner .nav-rm-review').bind('click', showcase.review.removeReview);	
			$('.modal-review .inner .nav-publish-review').bind('click', showcase.review.publishReview);
			$('.modal-review .inner .message')
				.bind('keyup', showcase.review.updateCount)
				.bind('blur', showcase.review.updateCount);

			if (data.reviews.length > 0) {
				$('.modal-review .inner .message').val(data.reviews[0].content);
				showcase.review.mode = 'update';
			}else{
				showcase.review.mode = 'insert';
			};
			
			showcase.review.showLayout(showcase.review.mode);	
			mlModal.hideLoading();
		},
		
		addEditComplete: function(data, stt, xhr){
			mlModal.close();
			if(showcase.review.mode == 'insert'){
				mlControls.alert(settings.review.msgValidate1);
			}else{
				mlControls.alert(settings.review.msgValidate2);
			}
		},
		
		publishReview: function(e){
			e.preventDefault();
			var isValid = true;
			
			if($('.modal-review .inner .message').val().length == 0){
				$('.modal-review .inner .message').next().addClass('error');
				isValid = false;
			}else{
				$('.modal-review .inner .message').next().removeClass('error');
			}
			
			if($('.modal-review .inner input[name="allow-terms"]:checked').length == 0){
				$('.modal-review .inner input[name="allow-terms"]').next('label').addClass('error');	
				isValid = false;
			}else{
				$('.modal-review .inner input[name="allow-terms"]').next('label').removeClass('error');	
			}
			
			if(!isValid) return;

			var jData = new mlSerializer()
				.add('product_id', showcase.review.prodId)
				.add('author_id', showcase.review.mlvcId)
				.add('content', $('.modal-review .inner .message').val())
				.render();

			$.ajax({
				type: 'post',
				dataType: 'json',
				contentType: 'application/json',
				processData: false,
				data: jData,
				url: settings.review.createUpdate,
				success: showcase.review.addEditComplete
			});
		},
		
		removeReview: function(e){
			e.preventDefault();
			
			mlControls.confirm(settings.review.msgValidate3, function(ok){
				if (!ok) return;
				
				var jData = new mlSerializer()
					.add('product_id', showcase.review.prodId)
					.add('author_id', showcase.review.mlvcId)
					.render();

				$.ajax({
					type: 'post',
					dataType: 'json',
					contentType: 'application/json',
					processData: false,
					data: jData,
					url: settings.review.delete,
					success: showcase.review.deleteComplete
				});
			});
		},
		
		deleteComplete: function(data, stt, xhr){
			mlModal.close();
			mlControls.alert(settings.review.msgValidate4);
		},

		updateCountTmOut: null,
		updateCount: function(e){
			clearTimeout(showcase.review.updateCountTmOut);
			
			var input = $('.modal-review .inner .message');
			var l = 250;
			
			$('.modal-review .inner .count').text(l - input.val().length);
			
			if(input.val().length >= l) {
				input.val(input.val().substr(0, l));
				return;
			}
			
			showcase.review.updateCountTmOut = setTimeout(showcase.review.updateCount, 1000);
		},
		
		showLayout: function(mode){
			if (mode == 'insert') {
				$('.modal-review .inner .nav-rm-review').hide();	
				$('.modal-review .inner .chk-terms').show();	
				$('.modal-review .inner .lbl-terms').show();	
				$('.modal-review .inner .count').show();	
				$('.modal-review .inner .nav-publish-review').show();	
				$('.modal-review .inner .msg-status').hide();	
				showcase.review.updateCount();
				
			}else if(mode == 'update'){
				$('.modal-review .inner .nav-rm-review').show();	
				$('.modal-review .inner .chk-terms').show();	
				$('.modal-review .inner .lbl-terms').show();	
				$('.modal-review .inner .count').show();	
				$('.modal-review .inner .nav-publish-review').show();	
				$('.modal-review .inner .msg-status').hide();	
				showcase.review.updateCount();

			}else if(mode == 'success'){
				$('.modal-review .inner .nav-rm-review').hide();	
				$('.modal-review .inner .chk-terms').hide();	
				$('.modal-review .inner .lbl-terms').hide();	
				$('.modal-review .inner .count').hide();	
				$('.modal-review .inner .nav-publish-review').hide();	
				$('.modal-review .inner .msg-status').show();	
			}		
		}
	},
	
	resultsFake: function() {
		for(var i = 0; i < 60; i++){
			var el = $('<li/>')
				.addClass('ml-li-prod-item')
				.text('Produto {0}'.format( (i + 1).toString() ) )
				.attr('rel', '{0}.eq({0})'.format(i.toString()))
				.appendTo('.vitrine .left-content .box-results ul');
		}
		
		$('.vitrine .left-content .box-results ul li').draggable({
			appendTo: 'body',
			helper: 'clone',
			start: function(e, ui) {
				$('.vitrine .central-content .current .drop-handler').show();
				$('.vitrine .central-content .lst-tabs .tab-content ul').addClass('target');
			}, stop: function(e, ui) {
				$('.vitrine .central-content .current .drop-handler').hide();	
				$('.vitrine .central-content .lst-tabs .tab-content ul').removeClass('target');
			}
		});
	},
	
	adjustPosition: function(){
		var currentFound = false;
		var foo = 133;
		
		$.each($('.vitrine .central-content .lst-tabs > ul > li'), function(i, _el){
			var el = $(_el);
			var pos = currentFound ? (foo * i) + 23 : (foo * i);
			
			el.find('.nav-tab').css('left', pos);
			
			if(el.hasClass('current')) currentFound = true;
		});
	}
};

$(document).ready(showcase.init);